package com.devg.file.web.utils;

import java.io.File;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CommonUtil {

  public static final String TOKEN = "token"; //设置用户cookie信息
  public static final String defaultDateFormat = "yyyy-MM-dd HH:mm:ss";
  public static final int maxAge = 25;  // token 超时时间

  public static String getSeqValue() {
    SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmssSSS");
    Random ne = new Random();
    int x = ne.nextInt(9999 - 1000 + 1) + 1000;
    return (sdf.format(new Date()) + x);
  }

  public static String getNowTime(String format) {
    SimpleDateFormat sdf = null;
    try {
      sdf = new SimpleDateFormat(format);
    } catch (Exception ex) {
      sdf = new SimpleDateFormat("yyyyMMdd");
    }
    return (sdf.format(new Date()));
  }

  public static String getToken(String loginName) {
//    int random = new Random().nextInt(900) + 100;
//    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//    String time = sdf.format(new Date());
//    return "LoginUser:" + loginName + ":" + time + random;
    String uuid = UUID.randomUUID().toString();
    return "loginUser:" + loginName + ":" + uuid;
  }

  public static Short getMapShort(Map<String, Object> map, String string) {
    return map == null ? null : map.get(string) == null ? null : Short.parseShort(map.get(string).toString());
  }

  public static Integer getMapInteger(Map<String, Object> map, String string) {
    return map == null ? null : map.get(string) == null ? null : Integer.parseInt(map.get(string).toString());
  }

  public static Integer getMapInteger(Map<String, Object> map, String string,Integer defaultValue) {
    return map == null ? defaultValue : map.get(string) == null ? defaultValue : Integer.parseInt(map.get(string).toString());
  }


  public static String getMapString(Map<String, Object> map, String string) {
    return map == null ? null : map.get(string) == null ? null : map.get(string).toString();
  }

  public static String getMapStringEmpty(Map map, String string) {
    return map == null ? "" : map.get(string) == null ? "" : map.get(string).toString();
  }

  public static BigDecimal getMapBigDecimal(Map map, String string) {
    return map == null ? BigDecimal.ZERO : map.get(string) == null ? BigDecimal.ZERO
        : new BigDecimal(String.valueOf(map.get(string)));
  }

  public static Long getMapLong(Map map, String string) {
    return map == null ? null : map.get(string) == null ? null : Long.valueOf(map.get(string).toString());
  }

  public static Long getMapLong(Map map, String string, Long defaultValue) {
    return map == null ? defaultValue : map.get(string) == null ? defaultValue : Long.valueOf(map.get(string).toString());
  }

  public static List getMapList(Map map, String string) {
    return map == null ? null : map.get(string) == null ? null : (List) map.get(string);
  }

  public static Object getMapObject(Map map, String string) {
    return map == null ? null : map.get(string);
  }

  public static String[] getMapStringArray(Map map, String string) {
    return map == null ? null : map.get(string) == null ? null : (String[]) map.get(string);
  }

  public static List<String> getMapStringList(Map map, String string) {
    return map == null ? null : map.get(string) == null ? null : (List<String>) map.get(string);
  }

  public static Date mapToDate(Map map, String string) {
    return map == null ? null : map.get(string) == null ? null : (Date) map.get(string);
  }

  public static Map mapToMap(Map map, String string) {
    return map == null ? null : map.get(string) == null ? null : (Map) map.get(string);
  }

  public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
  }

  public static boolean isEmpty(String[] strArray) {
    return strArray == null || strArray.length <= 0;
  }

  public static boolean isEmpty(List list) {
    return list == null || list.size() <= 0;
  }

  public static boolean isEmpty(Object object) {
    return object == null;
  }

  public static Boolean eq(Object o1, Object o2) {
    return null != o1 && o1.equals(o2);
  }

  public static Date strToDate(String date, String format) {
    try {
      SimpleDateFormat sdf = new SimpleDateFormat(format);
      return sdf.parse(date);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public static Date strToDate(String date) {
    return strToDate(date, defaultDateFormat);
  }

  public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
    Map<String, Object> map = new HashMap<>();
    Class<?> clazz = obj.getClass();
    for (Field field : clazz.getDeclaredFields()) {
      field.setAccessible(true);
      String fieldName = field.getName();
      Object value = field.get(obj);
      map.put(fieldName, value);
    }
    return map;
  }

  /**
   * 利用正则表达式判断字符串是否是数字
   */
  public static boolean isNumeric(String str) {
    Pattern pattern = Pattern.compile("[0-9]*");
    Matcher isNum = pattern.matcher(str);
    if (!isNum.matches()) {
      return false;
    }
    return true;
  }

  public static String getCookieValue(HttpServletRequest request, String cookieName) {
    // TODO Auto-generated method stub
    String cookieValue = null;
    Cookie[] cookies = request.getCookies(); // 这样便可以获取一个cookie数组
    if (null != cookies && cookies.length > 0) {
      for (Cookie cookie : cookies) {
        String coolieName = cookie.getName();
        if (null != coolieName && coolieName.equals(cookieName)) { // cookie存在登录成功
          cookieValue = cookie.getValue();
          break;
        }
      }
    }
    return cookieValue;
  }

  public static void setCookieValue(
      HttpServletResponse response, String name, String value, int maxAge) {
    // TODO Auto-generated method stub
    setCookieValue(response, name, value, maxAge, true);
  }

  public static void setCookieValue(
      HttpServletResponse response, String name, String value, int maxAge, boolean httpOnly) {
    // TODO Auto-generated method stub
    Cookie cookie = new Cookie(name, value); // 设置cookie和redis超时时间
    cookie.setMaxAge(maxAge); //单位秒
    cookie.setPath("/");
    if (httpOnly) {
      cookie.setHttpOnly(true);
    }
    response.addCookie(cookie);
  }

  /**
   * demo: StringUtils.filterShowColumn(list, "a", "b", "c"); demo: String[] s = {"a","b","c"} ;StringUtils.filterShowColumn(list, s);
   *
   * @param list
   * @param showColumn
   */
  public static void filterShowColumn(List<Map<String, Object>> list, String... showColumn) {
    if (null == list && list.size() <= 0) {
      return;
    }
    if (null == showColumn || showColumn.length < 0) {
      return;
    }
    for (Map<String, Object> map : list) {
      filterShowColumn(map, showColumn);
    }
  }

  public static void filterShowColumn(Map<String, Object> map, String... showColumn) {
    if (null == map || map.isEmpty()) {
      return;
    }
    Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
    while (iter.hasNext()) {
      Entry<String, Object> iterMap = iter.next();
      String key = iterMap.getKey();
      if (!Arrays.asList(showColumn).contains(key)) {
        iter.remove();
      }
    }
  }

  public static void main(String args[]) {
    List<Map<String, Object>> list = new ArrayList<>();
    Map<String, Object> map = new HashMap<>();
    map.put("a", "123");
    map.put("b", strToDate("2018-04-21 08:33:00"));
    list.add(map);
    map = new HashMap<>();
    map.put("a", "456");
    map.put("b", strToDate("2018-04-21 08:44:00"));
    list.add(map);
    map = new HashMap<>();
    map.put("a", "123");
    map.put("b", strToDate("2018-04-21 08:22:00"));
    list.add(map);
    System.out.println();
//        Collections.sort(list, new Comparator<Map<String,Object>>() {
//            @Override
//            public int compare(Map<String, Object> map1, Map<String, Object> map2) {
//                String a1 = mapToString(map1,"a");
//                String a2 = mapToString(map2,"a");
//                if(a1.compareTo(a2)>0){
//                    return 1;
//                }else if(a1.compareTo(a2)<0){
//                    return -1;
//                }else{
//                    Date dt1 = mapToDate(map1,"b");
//                    Date dt2 = mapToDate(map2,"b");
//                    if (dt1.getTime() > dt2.getTime()) {
//                        return 1;
//                    } else if (dt1.getTime() < dt2.getTime()) {
//                        return -1;
//                    } else {
//                        return 0;
//                    }
//                }
//            }
//        });
    list.sort((Map<String, Object> map1, Map<String, Object> map2) -> {
      String a1 = getMapStringEmpty(map1, "a");
      String a2 = getMapStringEmpty(map2, "a");
      if (a1.compareTo(a2) > 0) {
        return 1;
      } else if (a1.compareTo(a2) < 0) {
        return -1;
      } else {
        Date dt1 = mapToDate(map1, "b");
        Date dt2 = mapToDate(map2, "b");
        if (dt1.getTime() > dt2.getTime()) {
          return 1;
        } else if (dt1.getTime() < dt2.getTime()) {
          return -1;
        } else {
          return 0;
        }
      }
    });
    list.forEach((Map<String, Object> m) -> {
      System.out.println(m.get("a") + "," + m.get("b"));
    });
  }

  public static String changePath(String filePath) {
    if (!filePath.endsWith(File.separator)) {
      filePath += File.separator;
    }
    return filePath;
  }

}
